package com.cnap.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.cnap.config.CloudMgmtConfig;
import com.cnap.model.cloud.*;
import com.cnap.model.cloud.scaling.CreateScalingDTO;
import com.cnap.model.exception.JsonException;
import com.cnap.service.CloudMgmtService;
import com.cnap.utils.JsonUtil;
import com.cnap.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <类文件描述>
 *
 * @author xc
 **/
@Service
public class CloudMgmtServiceImpl implements CloudMgmtService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CloudMgmtServiceImpl.class);

    private static final String CREATE_RESOURCE_URL = "/cnap/multicloudmgmt/v1/vm/createVmResource";
    private static final String CREATE_RESOURCE_WITHOUT_TOKEN_URL = "/cnap/multicloudmgmt/v1/be/createVmResource";
    private static final String DELETE_LOCAL_IMAGE_URL = "/cnap/multicloudmgmt/v1/be/delNodeImage";
    private static final String DELETE_URL = "/cnap/multicloudmgmt/v1/be/delSvcToVmCreate";
    private static final String CREATE_SCALING_URL = "/cnap/multicloudmgmt/v1/clusterInfo/create-default";
    private static final String QUERY_SCALING_URL = "/cnap/multicloudmgmt/v1/scaling/group/list";
    private static final String DELETE_INDICATOR_HISTORY_URL = "/cnap/multicloudmgmt/v1/be/delSvcHandler";


    private final CloudMgmtConfig cloudMgmtConfig;

    @Autowired
    public CloudMgmtServiceImpl(CloudMgmtConfig cloudMgmtConfig) {
        this.cloudMgmtConfig = cloudMgmtConfig;
    }

    /**
     * 创建云资源
     *
     * @param createCloudParam 参数
     * @return 结果
     */
    @Override
    public CommentResultForCloud createCloudResource(CreateCloudParam createCloudParam) {
        // 获取token
        String token = TokenUtils.getTOKEN();
        if (Objects.isNull(token)) {
            LOGGER.error("token is null");
            throw new JsonException(401, "token已过期");
        }
        LOGGER.info("send request to multi system: {}", createCloudParam);
        String realUrl = cloudMgmtConfig.getUrl() + CREATE_RESOURCE_URL;
        HttpResponse response = HttpRequest.post(realUrl).header(HttpHeaders.AUTHORIZATION, token).body(JsonUtil.objectToJsonStr(createCloudParam)).execute();
        if (!response.isOk()) {
            LOGGER.error("can't get right response from multi cloud, response={}", response);
            throw new JsonException(500, "服务器内部错误");
        }
        CommentResultForCloud result = JsonUtil.jsonStrToObject(response.body(), CommentResultForCloud.class);
        // 防止接口变更
        if (Objects.isNull(result)) {
            LOGGER.error("can't parse multi cloud response, response={}", response);
            throw new JsonException(500, "服务器内部错误");
        }
        if (result.getCode() != 200) {
            LOGGER.error("multi cloud error, {}", result.getMessage());
            throw new JsonException(500, result.getMessage());
        }
        return result;
    }

    @Override
    public CommentResultForCloud createCloudResourceWithoutToken(CreateCloudParam createCloudParam) {
        LOGGER.info("send request to multi system without token: {}", createCloudParam);
        String realUrl = cloudMgmtConfig.getUrl() + CREATE_RESOURCE_WITHOUT_TOKEN_URL;
        HttpResponse response = HttpRequest.post(realUrl).body(JsonUtil.objectToJsonStr(createCloudParam)).execute();
        if (!response.isOk()) {
            LOGGER.error("can't get right response from multi cloud, response={}", response);
            throw new JsonException(500, "服务器内部错误");
        }
        CommentResultForCloud result = JsonUtil.jsonStrToObject(response.body(), CommentResultForCloud.class);
        // 防止接口变更
        if (Objects.isNull(result)) {
            LOGGER.error("can't parse multi cloud response, response={}", response);
            throw new JsonException(500, "服务器内部错误");
        }
        if (result.getCode() != 200) {
            LOGGER.error("multi cloud error, {}", result.getMessage());
            throw new JsonException(500, result.getMessage());
        }
        return result;
    }

    /**
     * 删除本地镜像
     *
     * @param deleteLocalImageParam 参数
     * @return 结果
     */
    @Override
    public CommentResultForCloud deleteLocalImageByServiceInfo(DeleteLocalImageParam deleteLocalImageParam) {
        LOGGER.info("send request to multi system: {}", deleteLocalImageParam);
        String realUrl = cloudMgmtConfig.getUrl() + DELETE_LOCAL_IMAGE_URL;
        HttpResponse response =
                HttpRequest.post(realUrl).body(JsonUtil.objectToJsonStr(deleteLocalImageParam)).execute();
        if (!response.isOk()) {
            LOGGER.error("can't get right response from multi cloud, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        CommentResultForCloud result = JsonUtil.jsonStrToObject(response.body(), CommentResultForCloud.class);
        // 防止接口变更
        if (Objects.isNull(result)) {
            LOGGER.error("can't parse multi cloud response, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        if (result.getCode() != 200) {
            LOGGER.error("multi cloud error, {}", result.getMessage());
            return CommentResultForCloud.errorResponseWithCode500();
        }
        return result;
    }

    @Override
    public CommentResultForCloud insertNewScalingPolicy(List<CreateScalingDTO> createScalingDTOs) {
        String realUrl = cloudMgmtConfig.getUrl() + CREATE_SCALING_URL;
        HttpResponse response =
                HttpRequest.post(realUrl).body(JsonUtil.objectToJsonStr(createScalingDTOs)).execute();
        if (!response.isOk()) {
            LOGGER.error("can't get right response from multi cloud, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        CommentResultForCloud result = JsonUtil.jsonStrToObject(response.body(), CommentResultForCloud.class);
        // 防止接口变更
        if (Objects.isNull(result)) {
            LOGGER.error("can't parse multi cloud response, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        if (result.getCode() != 200) {
            LOGGER.error("multi cloud error, {}", result.getMessage());
            return CommentResultForCloud.errorResponseWithCode500();
        }
        return result;
    }

    @Override
    public CommentResultForCloud deleteVmAndOtherInfo(DeleteParam deleteParam) {
        LOGGER.info("send request to multi system: {}", deleteParam);
        String realUrl = cloudMgmtConfig.getUrl() + DELETE_URL;
        HttpResponse response =
                HttpRequest.post(realUrl).body(JsonUtil.objectToJsonStr(deleteParam)).execute();
        if (!response.isOk()) {
            LOGGER.error("can't get right response from multi cloud, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        CommentResultForCloud result = JsonUtil.jsonStrToObject(response.body(), CommentResultForCloud.class);
        // 防止接口变更
        if (Objects.isNull(result)) {
            LOGGER.error("can't parse multi cloud response, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        if (result.getCode() != 200) {
            LOGGER.error("multi cloud error, {}", result.getMessage());
            return CommentResultForCloud.errorResponseWithCode500();
        }
        return result;
    }

    @Override
    public CommentResultForCloud deleteIndicatorHistory(DeleteIndicatorHistoryParam deleteIndicatorHistoryParam) {
        String realUrl = cloudMgmtConfig.getUrl() + DELETE_INDICATOR_HISTORY_URL;
        HttpResponse response =
                HttpRequest.post(realUrl).body(JsonUtil.objectToJsonStr(deleteIndicatorHistoryParam)).execute();
        if (!response.isOk()) {
            LOGGER.error("delete indicator history: can't get right response from multi cloud, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        CommentResultForCloud result = JsonUtil.jsonStrToObject(response.body(), CommentResultForCloud.class);
        // 防止接口变更
        if (Objects.isNull(result)) {
            LOGGER.error("delete indicator history: can't parse multi cloud response, response={}", response);
            return CommentResultForCloud.errorResponseWithCode500();
        }
        if (result.getCode() != 200) {
            LOGGER.error("delete indicator history: multi cloud error, {}", result.getMessage());
            return CommentResultForCloud.errorResponseWithCode500();
        }
        return result;
    }
}
